package cn.knightzz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.knightzz.entity.SysMessage;
import cn.knightzz.entity.SysUser;
import cn.knightzz.entity.SysUserMessage;
import cn.knightzz.mapper.SysMessageMapper;
import cn.knightzz.mapper.SysUserMessageMapper;
import cn.knightzz.service.SysUserMessageService;
import cn.knightzz.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jdk.nashorn.internal.ir.annotations.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author knightzz
 * @since 2021-05-07
 */
@Slf4j
@Service
public class SysUserMessageServiceImpl extends ServiceImpl<SysUserMessageMapper, SysUserMessage> implements SysUserMessageService {

    @Resource
    SysUserMessageMapper userMessageMapper;

    @Resource
    SysMessageMapper messageMapper;

    @Resource
    SysUserService userService;


    /**
     * 批量添加消息与用户之间的关系
     * 默认 用户id列表为空 则向所有用户发送信息
     *
     * @param msgId      消息数据的id
     * @param userIdList 对应的用户id
     */
    @Override
    public void addUserMessageInfos(Long msgId, List<Long> userIdList) {

        // 判断用户列表是否为空
        // 如果为空 默认是向所有用户发送信息
        if (ObjectUtil.isNotNull(userIdList) && userIdList.isEmpty()) {
            List<SysUser> userList = userService.getUserList();
            for (SysUser sysUser : userList) {
                userIdList.add(sysUser.getId());
            }
        }

        SysUserMessage userMessage;
        for (Long userId : userIdList) {
            userMessage = new SysUserMessage();
            userMessage.setUserId(userId);
            userMessage.setMsgId(msgId);
            userMessageMapper.insert(userMessage);
        }
    }

    /**
     * 根据当前用户的 id 获取其所有的通知
     *
     * @param userId
     * @return 通知列表
     */
    @Override
    public List<SysMessage> getMessageByUserId(Long userId) {
        List<SysMessage> messageByUserId;
        try {
            messageByUserId = userMessageMapper.getMessageByUserId(userId);
        } catch (Exception e) {
            log.error("getMessageByUserId error ...");
            log.error(e.getMessage());
            return new ArrayList<>();
        }
        return messageByUserId;
    }

}
